
package kaizone.haining.chaobohui.setup;

import java.io.IOException;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.keep.AccessTokenKeeper;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.sso.SsoHandler;
import com.weibo.sdk.android.util.Utility;

public class XinLangWeiBo extends Shareter {

    private static final String TAG = "XinLanWeiBo";

    private static final String CONSUMER_KEY = "966056985"; // "1352418311";
                                                            // //"4073611897";//
                                                            // 替换为开发者的appkey，

    private static final String REDIRECT_URL = "http://www.sina.com";

    public static int isBinding = 0;

    public static Oauth2AccessToken accessToken;

    private boolean mIsAuthorizing;

    private Weibo mWeibo;

    private Context mContext;

    SsoHandler mSsoHandler;

    public XinLangWeiBo(Context context) {
        super(context);
        mContext = context;
        initWeibo();
    }

    public void initWeibo() {
        mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
        try {
            Class sso = Class.forName("com.weibo.sdk.android.sso.SsoHandler");
        } catch (ClassNotFoundException e) {
            Log.i(TAG, "com.weibo.sdk.android.sso.SsoHandler not found");
        }
        accessToken = AccessTokenKeeper.readAccessToken(mContext);
        if (accessToken.isSessionValid()) {
            Weibo.isWifi = Utility.isWifi(mContext);
            try {
                Class sso = Class.forName("com.weibo.sdk.android.api.WeiboAPI");// 如果支持weiboapi的话，显示api功能演示入口按钮
            } catch (ClassNotFoundException e) {
                // e.printStackTrace();
                Log.i(TAG, "com.weibo.sdk.android.api.WeiboAPI not found");

            }
            String date = new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss")
                    .format(new java.util.Date(accessToken.getExpiresTime()));
            Toast.makeText(
                    mContext,
                    "access_token 仍在有效期内,无需再次登录: \naccess_token:" + accessToken.getToken()
                            + "\n有效期：" + date, 200).show();
        } else {
            Toast.makeText(mContext,
                    "使用SSO登录前，请检查手机上是否已经安装新浪微博客户端，目前仅3.0.0及以上微博客户端版本支持SSO；如果未安装，将自动转为Oauth2.0进行认证",
                    200).show();
        }
    }

    public boolean isSessionValid() {
        return accessToken.isSessionValid();
    }

    public void authorize(Context ctx) {
        // if (mIsAuthorizing)
        // return;
        if (ctx != null) {
            mWeibo.authorize(ctx, new AuthDialogListener());
            mIsAuthorizing = true;
        }
    }

    public void authorizeSso() {
        if (mIsAuthorizing)
            return;
        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            mSsoHandler = new SsoHandler(activity, mWeibo);
            mSsoHandler.authorize(new AuthDialogListener());
            mIsAuthorizing = true;
        }
    }

    private void endAuthorize() {
        mIsAuthorizing = false;
    }

    public void update(String content, String lat, String lon) {
        StatusesAPI api = new StatusesAPI(accessToken);
        api.update(content, lat, lon, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_IOEXCEPTION, arg0.toString());
            }

            @Override
            public void onError(WeiboException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_ERROR, arg0.toString());
            }

            @Override
            public void onComplete(String arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_COMPLETE, arg0);
            }
        });
    }

    public void upload(String content, String file, String lat, String lon) {
        StatusesAPI api = new StatusesAPI(accessToken);
        api.upload(content, file, lat, lon, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_IOEXCEPTION, arg0.toString());
            }

            @Override
            public void onError(WeiboException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_IOEXCEPTION, arg0.toString());
            }

            @Override
            public void onComplete(String arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_IOEXCEPTION, arg0.toString());
            }
        });
    }

    public void uploadUrlText(String status, String imageUrl, String lat, String lon) {
        StatusesAPI api = new StatusesAPI(accessToken);
        api.uploadUrlText(status, imageUrl, lat, lon, new RequestListener() {
            @Override
            public void onIOException(IOException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_IOEXCEPTION, arg0.toString());
            }

            @Override
            public void onError(WeiboException arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_ERROR, arg0.toString());
            }

            @Override
            public void onComplete(String arg0) {
                sendMsgToUi(FALG_FX, RESPONSE_COMPLETE, arg0);
            }
        });
    }

    public void clear() {
        AccessTokenKeeper.clear(mContext);
    }

    class AuthDialogListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            accessToken = new Oauth2AccessToken(token, expires_in);
            if (accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(accessToken.getExpiresTime()));
                Toast.makeText(
                        mContext,
                        "认证成功: \r\n access_token: " + token + "\r\n" + "expires_in: " + expires_in
                                + "\r\n有效期：" + date, 200).show();
                try {
                    Class sso = Class.forName("com.weibo.sdk.android.api.WeiboAPI");// 如果支持weiboapi的话，显示api功能演示入口按钮
                } catch (ClassNotFoundException e) {
                    // e.printStackTrace();
                    Log.i(TAG, "com.weibo.sdk.android.api.WeiboAPI not found");

                }
                AccessTokenKeeper.keepAccessToken(mContext, accessToken);
                Toast.makeText(mContext, "认证成功", Toast.LENGTH_SHORT).show();
                isBinding = 1;
            }
            // endAuthorize();
        }

        @Override
        public void onError(WeiboDialogError e) {
            Toast.makeText(mContext, "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
            // endAuthorize();
        }

        @Override
        public void onCancel() {
            Toast.makeText(mContext, "Auth cancel", Toast.LENGTH_LONG).show();
            // endAuthorize();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(mContext, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
            // endAuthorize();
        }
    }

}
